<template>
    <div>
        <van-nav-bar title="可漂出书籍" left-text="返回" left-arrow @click-left="goBack">
            <template #title>
                <span style="color: white;">可漂出书籍</span>
            </template>
            <template #left>
                <van-icon name="arrow-left" style="color: white; margin-right: 4px;"/>
                <span style="color: white;">返回</span>
            </template>
        </van-nav-bar>
        <div class="book-list-container">
            <!-- 搜索框 -->
            <div class="search-container">
                <van-search v-model="searchForm.title" placeholder="请输入书名" @search="onSearch" @clear="onClear"/>
                <!-- <van-search v-model="searchForm.isbn" placeholder="请输入ISBN" @search="onSearch" @clear="onClear"/> -->
            </div>

            <!-- 加载状态 -->
            <div class="load-main" v-if="showLoading && bookList.length === 0">
                <van-loading style="margin-bottom: 15px"/>
                <span>加载中</span>
            </div>

            <!-- 书籍列表 -->
            <div v-if="!showLoading || bookList.length > 0">
                <van-row v-for="(item) in bookList" :key="item.id" class="row-box">
                    <van-col span="24">
                        <div class="book-title">{{ item.title }}</div>
                    </van-col>
                    <van-col span="14">
                        <div class="book-info">
                            <span class="label">ISBN:</span>
                            <span class="value">{{ item.isbn }}</span>
                        </div>
                    </van-col>
                    <van-col span="10">
                        <div class="book-info" style="text-align: right;">
                            <span class="label">入库:</span>
                            <span class="value">{{ formatTimestampToDate(item.storeTime) }}</span>
                        </div>
                    </van-col>
                </van-row>
            </div>

            <!-- 无数据提示 -->
            <div class="nodata-main" v-if="!showLoading && bookList.length === 0">
                暂无数据
            </div>

            <!-- 加载更多 -->
            <div class="load-more" v-if="hasMore && bookList.length > 0">
                <van-loading v-if="loadingMore" style="margin-right: 10px"/>
                <span v-if="loadingMore">加载中...</span>
                <span v-else-if="!hasMore">没有更多了</span>
            </div>
        </div>

        <!-- 返回顶部按钮 -->
        <van-back-top v-if="showBackTop" @click="scrollToTop"/>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
//@ts-ignore
import { bookApi } from '../api/lbBook.ts';
import { showToast } from 'vant';

const router = useRouter();

const goBack = () => {
    router.push({ path: '/home' });
};

// 搜索表单
const searchForm = ref({
    title: '',
    isbn: ''
});

// 分页参数
const pageParams = ref({
    pageNo: 1,
    pageSize: 10
});

// 数据状态
const bookList = ref([]);
const showLoading = ref(false);
const loadingMore = ref(false);
const hasMore = ref(true);
const showBackTop = ref(false);

// 格式化时间戳
const formatTimestampToDate = (timestamp: number): string => {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

// 获取书籍列表
const getBookList = async (isLoadMore = false) => {
    if (isLoadMore) {
        loadingMore.value = true;
    } else {
        showLoading.value = true;
        pageParams.value.pageNo = 1;
        bookList.value = [];
    }

    try {
        const params = {
            pageNo: pageParams.value.pageNo,
            pageSize: pageParams.value.pageSize,
            title: searchForm.value.title,
            isbn: searchForm.value.isbn
        };

        const response = await bookApi.getInLwBookPage(params);

        // 响应拦截器已经处理了code判断，这里直接使用返回的data
        const newBooks = response.list || [];

        if (isLoadMore) {
            bookList.value = [...bookList.value, ...newBooks];
        } else {
            bookList.value = newBooks;
        }

        // 判断是否还有更多数据
        hasMore.value = bookList.value.length < response.total;

        if (hasMore.value) {
            pageParams.value.pageNo++;
        }
    } catch (error) {
        console.error('获取书籍列表失败:', error);
        showToast('网络错误，请稍后重试');
    } finally {
        showLoading.value = false;
        loadingMore.value = false;
    }
};

// 搜索
const onSearch = () => {
    getBookList();
};

// 清空搜索
const onClear = () => {
    getBookList();
};

// 滚动到顶部
const scrollToTop = () => {
    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
};

// 滚动事件处理
const handleScroll = () => {
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;

    // 显示返回顶部按钮
    showBackTop.value = scrollTop > 300;

    // 触底加载更多
    const windowHeight = window.innerHeight;
    const documentHeight = document.documentElement.scrollHeight;

    if (scrollTop + windowHeight >= documentHeight - 100) {
        if (hasMore.value && !loadingMore.value && !showLoading.value) {
            getBookList(true);
        }
    }
};

// 生命周期
onMounted(() => {
    getBookList();
    window.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
});
</script>

<style scoped lang="scss">
.book-list-container {
    padding: 1rem;
    min-height: calc(100vh - 46px);
    background-color: #f5f5f5;
}

.search-container {
    margin-bottom: 1rem;

    .van-search {
        margin-bottom: 0.5rem;
        background-color: white;
        border-radius: 6px;
    }
}

.row-box {
    background-color: white;
    padding: 1rem;
    margin-bottom: 0.8rem;
    border-radius: 6px;
    box-shadow: 0 4px 10px rgb(175 175 175 / 10%);
}

.book-title {
    font-size: 1rem;
    font-weight: bold;
    color: #059669;
    margin-bottom: 0.5rem;
    line-height: 1.4;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.book-info {
    margin-bottom: 0.3rem;
    font-size: 0.9rem;

    .label {
        color: #666;
        margin-right: 0.5rem;
    }

    .value {
        color: #333;
    }
}

.text-a-r {
    text-align: right;
}

.load-main {
    text-align: center;
    color: rgb(204, 204, 204);
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    height: 300px;
}

.nodata-main {
    text-align: center;
    color: #ccc;
    height: 200px;
    line-height: 200px;
    font-size: 1rem;
}

.load-more {
    text-align: center;
    padding: 1rem;
    color: #666;
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep .van-back-top {
    right: 20px;
    bottom: 80px;
    background-color: #059669;

    .van-icon {
        color: white;
    }
}

::v-deep .van-nav-bar {
    background-color: #059669;

    .van-nav-bar__content {
        background-color: #059669;
    }
}


</style>
